<?php
class SysUserBusi {
	// 查询一个用户的可访问祖先菜单
	public function queryUserVisitRootMenus($condition) {
		global $mysqlTools;
		
		// 参数处理注入SQL安全问题
		$condition = $mysqlTools->check_input ( $condition );
		
		$menus = $mysqlTools->selectSql ( "
			select 
				sm.menuId as id,
				sm.menuName,
				sm.menuOrder,
				sm.menuUrl,
				sm.menuDesc as title,
				sm.menuParentId,
				sm.menuIsUsed,
				sm.menuIsActive,
				sm.menuIsSingle,
				true as isFixed
			from 
			(
			(select srm.menuId from sys_role_menu srm where srm.roleId in 
			(select sur.roleId from sys_user_role sur where sur.userId =$condition[userId] ))
			union 
			(select sum.menuId from sys_user_menu sum where sum.userId=$condition[userId] )
			) s left join sys_menu sm on s.menuId = sm.menuId
			where sm.menuParentId = 0 and 
				sm.menuIsUsed=1
			order by sm.menuOrder asc
		" );
		
		return $menus;
	}
	
	// 查询一个父类菜单查询子菜单信息递归，只能是该用户拥有的子菜单
	public function queryUserVisitMenusByParentMenuId($condition) {
		global $mysqlTools;
		
		// 参数处理注入SQL安全问题
		$condition = $mysqlTools->check_input ( $condition );
		
		$menus = $mysqlTools->selectSql ( "
			select
			sm.menuId,
			sm.menuName,
			sm.menuOrder,
			sm.menuUrl,
			sm.menuDesc,
			sm.menuParentId,
			sm.menuIsUsed,
			sm.menuIsActive,
			sm.menuIsSingle,
			1 as menuType,
			1 as menuIsActive,
			true as isFixed
			from
			(
			(select srm.menuId from sys_role_menu srm where srm.roleId in
			(select sur.roleId from sys_user_role sur where sur.userId =$condition[userId] ))
			union
			(select sum.menuId from sys_user_menu sum where sum.userId=$condition[userId] )
			) s left join sys_menu sm on s.menuId = sm.menuId
			where sm.menuParentId = $condition[menuParentId] and 
				sm.menuIsUsed=1
			order by sm.menuOrder asc
		" );
		
		if (count ( $menus ) > 0) {
			foreach ( $menus as $i => $menu ) {
				// 查询该菜单还有子菜单没有
				$childrenMenus = $mysqlTools->selectSql ( "
					select
					sm.menuId,
					sm.menuName,
					sm.menuOrder,
					sm.menuUrl,
					sm.menuDesc,
					sm.menuParentId,
					sm.menuIsUsed,
					sm.menuIsActive,
					sm.menuIsSingle
					from
						sys_menu sm 
					where sm.menuParentId = $menu[menuId] and
						sm.menuIsUsed=1
					order by sm.menuOrder asc
				" );
				$menus [$i] ['menuChildren'] = $childrenMenus;
			}
		}
		
		return $menus;
	}
	
	// 查询一个用户是否拥有某个菜单权限
	public function queryUserVisitMenuIsPass($condition) {
		global $mysqlTools;
		
		// 参数处理注入SQL安全问题
		$condition = $mysqlTools->check_input ( $condition, array (
				'method' 
		) );
		
		$menus = $mysqlTools->selectSql ( "
			select sum.menuId,sm.menuUrl from sys_user_menu sum left join sys_menu sm on sum.menuId=sm.menuId 
			where sum.userId=$condition[userId] and sm.menuUrl like $condition[method]
			union
			select srm.menuId,sm.menuUrl from sys_role_menu srm left join sys_menu sm on srm.menuId=sm.menuId 
			where srm.roleId in ( 
			select sur.roleId from sys_user_role sur where sur.userId=$condition[userId]) 
			and sm.menuUrl like $condition[method]
		" );
		
		if (count ( $menus ) > 0)
			return true;
		else
			return false;
	}
	
	// 查询一个用户能够访问的所有菜单信息
	public function queryUserVisitAllMenus($condition) {
		global $mysqlTools;
		
		$WhereLike = "";
		if (isset ( $condition ["menuDesc"] )) {
			$WhereLike = " and sm.menuDesc like '%" . $condition ["menuDesc"] . "%'";
		}
		
		// 参数处理注入SQL安全问题
		$condition = $mysqlTools->check_input ( $condition );
		
		$menus = $mysqlTools->selectSql ( "
			select sum.menuId as id,sm.menuUrl,sm.menuDesc as name,sm.menuParentId as pId from sys_user_menu sum left join sys_menu sm on sum.menuId=sm.menuId 
			where sum.userId=$condition[userId]  $WhereLike
			union
			select srm.menuId as id,sm.menuUrl,sm.menuDesc as name,sm.menuParentId as pId from sys_role_menu srm left join sys_menu sm on srm.menuId=sm.menuId 
			where srm.roleId in ( 
			select sur.roleId from sys_user_role sur where sur.userId=$condition[userId]  $WhereLike)
		" );
		
		return $menus;
	}
	
	private function queryUserInfo($param){
		global $mysqlTools;
		$param = $mysqlTools->check_input ( $param );
		$sql = "
		SELECT
		su.userId,
		su.userLoginId,
		su.userPwd,
		su.userPhone,
		su.userRealName,
		su.userTel,
		su.userEmail,
		su.userAvatarId,
		su.userState,
		su.userCreateTime
		FROM
		sys_user su where
		su.userLoginId = $param[userLoginId] 
		";
		$sysUsers = $mysqlTools->selectSql ( $sql );
		$userInfo = null;
		if (is_array ( $sysUsers ) && ! empty ( $sysUsers )) {
			$userInfo = $sysUsers [0];
		}
		return $userInfo;
	}
	
	private function operateLoginError($param){
		$errorInfo = $this->queryLoginError($param);
		if(is_null($errorInfo)){
			$this->addLoginError($param);
		}else{
			$this->editLoginErrorCount(array("errId"=>$errorInfo["errId"]));
		}
	}
	
	private function allowLogin($param){
		$errorInfo = $this->queryLoginError($param);
		if(empty($errorInfo)){
			return true;
		}
		if((int)$errorInfo["errCount"]>4){
			return false;
		}
		return true;
	}
	
	private function queryLoginError($param){
		global $mysqlTools;
		$param["now"] = date("Y-m-d",time());
		$param = $mysqlTools->check_input ( $param );
		$sql = "
		SELECT
		errId,
		errUserId,
		errCount,
		errLoginTime
		FROM
		sys_login_error where 1=1
		and errUserId = $param[userId]
		and errLoginTime = $param[now]
		lock in share mode
		";
		$sysError= $mysqlTools->selectSql ( $sql );
		if (is_array ( $sysError ) && ! empty ( $sysError )) {
			return $sysError[0];
		}
		return null;
	}
	
	private function addLoginError($param){
		global $mysqlTools;
		$param["now"] = date("Y-m-d",time());
		$param = $mysqlTools->check_input ( $param );
		$uniqid = getCurrentId ();
		$sql = "
		insert into sys_login_error (errId,errUserId,errLoginTime,errCount)
		values($uniqid,$param[userId],$param[now],1)
		";
		$result = $mysqlTools->executeSql ( $sql );
		if (! $result) {
			return "添加登陆错误次数失败";
		}
		return "success";
	}
	
	private function editLoginErrorCount($param){
		global $mysqlTools;
		$param = $mysqlTools->check_input ( $param );
		$sql = "
			update sys_login_error set errCount = errCount+1 where errId = $param[errId]
		";
		$result = $mysqlTools->executeSql ( $sql );
		if (! $result) {
			return "修改登陆错误次数失败";
		}
		return "success";
	}
	
	/**
	 * 用户登录
	 */
	public function loginSysUser($condition) {
		global $mysqlTools, $redis, $cookieTools;
		$condition["userLoginId"] = trim($condition["userLoginId"]);
		$condition["userPwd"] = trim($condition["userPwd"]);
		if(!isset($condition["userLoginId"]) || empty($condition["userLoginId"])){
			return "用户名不能为空";
		}
		if(!isset($condition["userPwd"]) || empty($condition["userPwd"])){
			return "密码不能为空";
		}
		$validUser = $this->queryUserInfo($condition);
		$mysqlTools->startTransaction();
		if(!$this->allowLogin(array(
				"userId"=>$validUser["userId"]
		))){
			$mysqlTools->commitTransaction();
			return "输错密码次数超过限制,请过一天在试";
		}
		$guid = guid ();
		$params = $condition;
		$userPwd = md5 ( $condition ['userPwd'] );
		$condition = $mysqlTools->check_input ( $condition );
		$expireTime = 60 * 60;
		$sql = "
	            SELECT
	            su.userId,
	            su.userLoginId,
	            su.userPwd,
	            su.userPhone,
	            su.userRealName,
	            su.userTel,
	            su.userEmail,
	            su.userAvatarId,
	            su.userState,
	            su.userCreateTime
	            FROM
	            sys_user su where
	            su.userLoginId = $condition[userLoginId]  and
	            su.userPwd = '$userPwd'
	            ";
		$sysUsers = $mysqlTools->selectSql ( $sql );
		$userInfo = null;
		if (is_array ( $sysUsers ) && ! empty ( $sysUsers )) {
			$userInfo = $sysUsers [0];
		}
		if (! is_null ( $userInfo )) {
			if ($userInfo ['userState'] == 1) {
				// 如果查出来有数据就装入redis服务器
				$redis->set ( $guid, serialize ( $sysUsers [0] ), $expireTime );
				$cookieTools->setCookie ( "sessionId", $guid, 0 );
				$mysqlTools->commitTransaction();
				return "success";
			} else if ($userInfo ['userState'] == 2) {
				$mysqlTools->commitTransaction();
				return "该用户已被锁定";
			} else if ($userInfo ['userState'] == 3) {
				$mysqlTools->commitTransaction();
				return "该用户已被封号";
			} else if ($userInfo ['userState'] == 4) {
				$mysqlTools->commitTransaction();
				return "该用户还未激活";
			}
		} else {
			$user = $this->queryUserInfo(array(
					"userLoginId"=>$params["userLoginId"]
			));
			if($user == null){
				$mysqlTools->commitTransaction();
				return "该用户还未注册";
			}
			$this->operateLoginError(array("userId"=>$user["userId"]));
			$mysqlTools->commitTransaction();
			return "密码输入错误";
		}
		$mysqlTools->commitTransaction();
	}
}

?>